package com.supply.service.impl;

import com.supply.global.Constants;
import com.supply.mapper.LeaveBillMapper;
import com.supply.pojo.LeaveBill;
import com.supply.req.LeaveBillGroup;
import com.supply.service.LeaveProcessService;
import com.supply.utils.CopyUtil;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LeaveProcessServiceImpl implements LeaveProcessService {
    @Autowired
    private LeaveBillMapper leaveBillMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Override
    public int startLeave(LeaveBillGroup leaveBillGroup) {
        //插入请假单数据，并获得回填Id
        int insertRs = leaveBillMapper.insert(leaveBillGroup);
        System.out.println("插入后回填的数据：" + leaveBillGroup.getId());

        String key = Constants.LEAVE_KEY;
        //构建businessKey，该字段可以记录流程实例关联的请假单的Id，并且该字段是唯一标识
        String businessKey = key + "." + leaveBillGroup.getId();
        //设置该流程的审核人
        Map<String,Object> map = new HashMap<>();
        map.put("salesman",leaveBillGroup.getUserId().toString());
        map.put("personnelman",leaveBillGroup.getPersonnelman().toString());
        map.put("manger",leaveBillGroup.getManger().toString());

        //开启流程
        runtimeService.startProcessInstanceByKey(key,businessKey,map);
        return insertRs;
    }

    @Override
    public LeaveBill queryLeaveBillByTaskId(String taskId) {
        //根据taskId查询task任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //根据从task任务获取的processInstanceId获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId())
                .singleResult();
        //从流程实例中获取businessKey，进而获取请假单Id
        String businessKey = processInstance.getBusinessKey();
        String id = businessKey.split("\\.")[1];
        return leaveBillMapper.selectByPrimaryKey(Long.parseLong(id));
    }
}
